from __future__ import absolute_import, division, print_function, unicode_literals
import keras
from flask import Flask, escape, request

import tensorflow as tf
import numpy as np

# 设置中文显示，防止中文显示乱码
from pylab import mpl

app = Flask(__name__)

mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

# 加载数据集
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# 每个图像都映射到一个标签
class_names = ['T恤/上衣', '裤子', '套衫', '连衣裙', '外套',
               '凉鞋', '衬衫', '运动鞋', '包/袋', '脚踝靴']
test_images
graph = tf.get_default_graph()
def buildModel():
    # 图像归一化
    # 将矩阵存储的整数（0，255）归一化到（0，1）的浮点数
    global train_images
    global test_images
    train_images = train_images / 255.0
    test_images = test_images / 255.0

    # 以下用于创建模型
    model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28, 28)),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(10, activation='softmax')
    ])
    # 以下用于编译模型

    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    # 调用函数开始训练，epochs指定训练次数
    model.fit(train_images, train_labels, epochs=1)

    # 在测试集上完成准确率的评估,
    test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
    print('\nTest accuracy:', test_acc)  # 输出准确率
    model.save('111.h5')

# def prediction(result):
#     #global test_images
#     image_list = np.expand_dims(result, axis=0)
#     preds = model.predict_classes(image_list)
#     print(preds)
#     return "0000"
     #   class_names[np.argmax(predictions_single[0])]

import matplotlib.image as imglib
import matplotlib.pyplot as plt

def yuce(image):
    image_list = np.expand_dims(image, axis=0)
    image_list = image_list/255.0
    image_list = np.squeeze(image_list)
    print(image_list)
    pres = model.predict_classes(image_list)
    print(pres)
    print(pres[0])
    #print(test_labels)
    return class_names[pres[0]]

@app.route('/test1', methods=['GET', 'POST'])
def getimage():
 #   plt.imshow(test_images[6])
#    plt.show()
    file = request.files.get('file')
    result = imglib.imread(file)
    lable=yuce(result)
    return str(lable)

from keras.models import load_model
model = load_model('111.h5')
if __name__ == '__main__':
   # buildModel()
    app.run(host='0.0.0.0', port=5000)
